package sr.myserver.service.impl;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sr.myserver.commons.Constants;
import sr.myserver.commons.Result;
import sr.myserver.commons.TokenManager;
import sr.myserver.config.JwtConfig;
import sr.myserver.entity.SysUsers;
import sr.myserver.service.LoginService;
import sr.myserver.service.SysUsersService;
import sr.myserver.vo.Login;
import sr.myserver.vo.Passwd;
import sr.myserver.vo.common.Basic;

import javax.servlet.http.HttpServletResponse;
import java.util.Hashtable;

/**
 * 用户权限状态管理
 *
 * @author sirui
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    private static final Hashtable<String, String> USERS = new Hashtable<>();

    @Autowired
    SysUsersService sysUsersService;

    /**
     * 用户登录缓存增加
     *
     * @param userId 用户编号
     * @param value  token值
     */
    @Override
    public void add(String userId, String value) {
        USERS.put(userId, value);
    }

    /**
     * 用户登录缓存删除
     *
     * @param userId 用户编号
     */
    @Override
    public void remove(String userId) {
        USERS.remove(userId);
    }

    /**
     * 用户登录缓存获取
     *
     * @param userId 用户编号
     * @return token值
     */
    @Override
    public String get(String userId) {
        return USERS.get(userId);
    }

    /**
     * @param entity   登录请求参数
     * @param response http response 对象
     * @return
     */
    @Override
    public Basic.Response login(Login.Request entity, HttpServletResponse response) {
        SysUsers user = sysUsersService.get(entity.getUserId());
        if (user == null) {
            return Result.fail("输入信息有误！");
        } else {
            entity.setUserId(user.getAccount());
        }
        if (!user.getPass().equals(entity.getPasswd())) {
            return Result.fail("输入密码不正确！");
        }

        String token = JwtConfig.create(entity, user.getRoleId());

        add(user.getAccount(), token);
        TokenManager.setCookie(response, Constants.AUTHORIZATION, token);

        Login.Response result = new Login.Response(Result.OK, "认证成功", token);

        result.setUserId(entity.getUserId());
        result.setUserName(user.getName());
        return result;
    }

    /**
     * 修改密码
     *
     * @param entity 修改密码信息
     * @return 密码修改结果
     */
    @Override
    public Basic.Response updatePass(Passwd.Request entity) {
        SysUsers user = sysUsersService.get(entity.getUserId());
        if (user == null) {
            return Result.fail("输入信息有误！");
        }
        if (!user.getPass().equals(entity.getPasswd())) {
            return Result.fail("输入密码不正确！");
        }
        user.setPass(entity.getNewPasswd());
        sysUsersService.update(user);
        return Result.ok();
    }

}
